package com.zzy.ws;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatTypes;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.zzy.config.WSConfig;
import com.zzy.entity.JsonMessage;
import com.zzy.entity.Message;
import com.zzy.entity.User;
import com.zzy.entity.UserRelation;
import com.zzy.mapper.MessageMapper;
import com.zzy.mapper.UserMapper;
import com.zzy.mapper.UserRelationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@ServerEndpoint(value = "/chat" ,configurator = WSConfig.class)
public class WebChatRoom {

    public static Map<String,Session> sessionMap = new HashMap<>();
    private static ApplicationContext context;

    public static void getApplication(ApplicationContext applicationContext){
        context = applicationContext;
    }

    private static User userMessage;

    @OnOpen
    public void onOpen(Session session , EndpointConfig config){
        System.out.println("ws已连接");
        HttpSession httpSession = (HttpSession) session.getUserProperties().get(HttpSession.class.getName());
        User user = (User) httpSession.getAttribute("user");
        userMessage = user;
        System.out.println(user.getUsername());
        sessionMap.put(userMessage.getUsername(),session);
    }
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        MessageMapper messageMapper = context.getBean(MessageMapper.class);
        // todo 拿到用户名 和 好友名 返回userRelation对象 得到 mId 值 插入数据库
        System.out.println(message);
        JSONObject jsonObject = JSON.parseObject(message);
        JsonMessage jsonMessage = JSON.toJavaObject(jsonObject, JsonMessage.class);
        //获取mid值
        UserRelation userRelation = getUserRelation(jsonMessage.getName(), jsonMessage.getFriendName());
        Message message2 = new Message(userRelation.getMId(),jsonMessage.getName(),jsonMessage.getMess(),new Date());
        //插入数据
        messageMapper.insert(message2);

        //生成返回数据
        String result = JSON.toJSONString(message2);

        //发给指定用户
        for (String s : sessionMap.keySet()) {
            if (s.equals(jsonMessage.getFriendName())){
                Session session1 = sessionMap.get(s);
                session1.getBasicRemote().sendText(result);
            }
        }
    }
    @OnClose
    public void onClose(){
        System.out.println("ws已断开");

    }
    public UserRelation getUserRelation(String selfName,String friendName){
        UserMapper userMapper = context.getBean(UserMapper.class);
        UserRelationMapper relationMapper = context.getBean(UserRelationMapper.class);
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username",selfName);
        User self = userMapper.selectOne(wrapper);
        QueryWrapper<User> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("username",friendName);
        User friend = userMapper.selectOne(wrapper1);

        QueryWrapper<UserRelation> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("u_id",self.getUId());
        wrapper2.eq("f_id",friend.getUId());
        UserRelation userRelation = relationMapper.selectOne(wrapper2);

        return userRelation;

    }
}
